<template>
  <div class="mod-config">
    <div style="margin-bottom: 90px;">
      <el-divider content-position="left">顾客资料</el-divider>
      <el-form inline style="padding: 5px;">
        <el-row>
          <el-col :span="24">
            <el-form-item label="卡号">
              <el-input v-model="customerData.customerCard" @keyup.enter.native="getCustomerByCardNo()"></el-input>
            </el-form-item>
            <el-button-group style="margin-right: 15px;">
              <el-button type="primary" icon="el-icon-user" @click="openDialog('customer')">查询</el-button>
              <el-button type="primary" icon="el-icon-user" @click="getCustomerByCardNo">读取</el-button>
              <el-button type="primary" icon="el-icon-plus" @click="openDialog('addNewCustomer')">会员新增</el-button>
            </el-button-group>
            <div v-if="customerData.id" style="display: inline-block;">

              <el-radio-group v-model="sale.saleType" style="margin-right: 15px;" @change="saleTypeChange">
                <el-radio :label="4">框镜</el-radio>
                <el-radio :label="3">隐形</el-radio>
                <el-radio :label="5">辅料</el-radio>
              </el-radio-group>
            </div>
          </el-col>
          <el-col :span="24">
            <div v-if="customerData.id" style="display: inline-block;">
              <el-form-item label="销售人员">
                <el-select v-model="sale.salerUserId" style="margin-left: 5px;" @change="saleUserChange" filterable>
                  <el-option v-for="item in saleUserOptions" :key="item.id" :value="item.id" :label="item.realName"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="主检医生">
                <el-select v-model="sale.checkDoctorId" style="margin-left: 5px;" @change="checkDoctorChangeHandle" filterable>
                  <el-option v-for="item in doctorOptions" :key="item.id" :value="item.id" :label="item.realName"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="customerData.id">
          <el-form-item label="顾客姓名">
            <el-input style="width: 100px;" v-model="customerData.name" readonly></el-input>
          </el-form-item>
          <el-form-item label="顾客电话">
            <el-input style="width: 120px;" v-model="customerData.phone1" readonly></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-input style="width: 100px;" v-if="customerData.gender == 0" value="男" readonly></el-input>
            <el-input style="width: 100px;" v-if="customerData.gender == 1" value="女" readonly></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input style="width: 100px;" v-model="customerData.age" readonly></el-input>
          </el-form-item>
          <el-form-item label="会员卡类型">
            <el-input style="width: 100px;" v-model="customerData.cardType?'会员卡':'非会员卡'" readonly></el-input>
          </el-form-item>
          <el-form-item label="医院积分">
            <el-input style="width: 100px;" v-model="customerData.integral" readonly></el-input>
          </el-form-item>
          <el-form-item label="门店积分">
            <el-input style="width: 100px;" v-model="customerData.storesIntegral" readonly></el-input>
          </el-form-item>
          <el-button plain icon="el-icon-collection" style="margin-top: 4px;" @click="openDialog('customerDetail')">详情</el-button>
        </el-row>
      </el-form>
      <el-row style="margin-top: 5px;" :gutter="10" v-if="customerData.id && (sale.saleType != 5 || ( sale.saleType == 5 && optometry.optType))">
        <el-col :span="6">
          <el-tabs v-model="activeName" type="border-card" class="miui">
            <el-tab-pane label="提交处方" name="first">
              <el-table class="miui-table" :data="saleOptometryList" height="240px" ref="alreadyOPt" border
                highlight-current-row @current-change="handleCurrentChange">
                <el-table-column prop="optType" label="处方类型" width="85">
                  <template slot-scope="scope">
                    {{getDataType('optTypeData', scope.row.optType)}}
                  </template>
                </el-table-column>
                <el-table-column prop="optUserName" label="验光师" width="75"></el-table-column>
                <el-table-column prop="createTime" label="验光时间">
                  <template slot-scope="scope">
                    {{cutStr(scope.row.createTime)}}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="手填处方" name="second">
              <el-form inline>
                <el-form-item label="验光师">
                  <el-select v-model="sale.optUserId" style="width: 100px;" :disabled="!optometryFormEdit">
                    <el-option v-for="item in optometristOptions" :key="item.id" :value="item.id" :label="item.realName"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="处方类型">
                  <el-select v-model="optometry.optOutFlag" :disabled="!optometryFormEdit" @change="optOutFlagChange">
                    <el-option value='1' label="内部处方"></el-option>
                    <el-option value='2' label="外部处方"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="验光类型">
                  <el-select v-model="optometry.optType" :disabled="!optometryFormEdit" @change="optTypeChange">
                    <el-option v-for="item in bizData.optTypeData" :value="item.value" :label="item.label" :key="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="验光时间">
                  <el-date-picker v-model="optometry.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"
                    disabled></el-date-picker>
                </el-form-item>
                <el-button type="info" @click="clearOptometryForm">清空</el-button>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="视光检查" name="three">
              <el-table class="miui-table" :data="checkOptometryList" height="240px" ref="alreadyOPt" border
                highlight-current-row @current-change="handleCurrentChange1">
                <el-table-column prop="doctorName" label="验光师" width="75"></el-table-column>
                <el-table-column prop="createTime" label="验光时间">
                  <template slot-scope="scope">
                    {{cutStr(scope.row.medicalStartTime)}}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="18">
          <!-- 验光处方表 -->
          <!-- <el-form :model="optometryData" :rules="dataRule" ref="dataForm"> -->
          <optometry-table ref="optoTable" :optometry-data="optometry" :saleType="sale.saleType" :source="'sale'"></optometry-table>
          <!-- </el-form> -->
        </el-col>
      </el-row>
      <el-row v-if="customerData.id" class="margin-top15" :gutter="10">
        <el-col :span="8">
          <el-row>
            <el-divider content-position="left">套餐</el-divider>
            <div style="padding: 5px;">
              <el-button type="primary" class="margin-right10" @click="openDialog('chooseSetMeal')">套餐选择</el-button>
              <el-button type="primary" class="margin-right10" @click="openDialog('checkSetMeal')">套餐查看</el-button>
              <el-button type="primary" class="margin-right10" @click="restore">还原</el-button>
            </div>
          </el-row>
          <el-row class="margin-top15">
            <el-divider content-position="left">分类</el-divider>
            <div style="padding: 5px;">
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','1')">镜架</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','3')" v-if="sale.saleType != 3">镜片</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','4')" v-if="sale.saleType != 4">隐形</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','7')">耗材</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','9')">视光</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','6')">太阳镜</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','8')">老花镜</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','5')">护理液</el-button>
              <el-button type="primary" class="margin-top15 margin-right10" @click="openDialog('searchGoods','2')">配件</el-button>
            </div>

          </el-row>
          <el-row class="margin-top15">
            <el-divider content-position="left">优惠</el-divider>
            <div style="padding: 5px;">
              <el-button type="primary" v-if="sale.saleType == 4" @click="openDialog('searchGoods','1','1')">自架</el-button>
              <el-button type="primary" v-if="sale.saleType == 4" @click="openDialog('searchGoods','3','1')">自镜</el-button>
              <el-button type="primary" @click="openGiftInfo">赠品</el-button>
            </div>
          </el-row>
          <el-row class="margin-top15">
            <el-divider content-position="left">其他</el-divider>
            <el-form>
              <el-form-item label="附加费用">
                <el-select v-model="addfee" @change="addFeeChange" filterable default-first-option>
                  <el-option v-for="item in addFeeOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="加工要求">
                <el-select v-model="maching" @change="machIngChange">
                  <el-option v-for="item in bizData.processingRequirementsData" :value="item.value" :label="item.label"
                    :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-row>
        </el-col>
        <el-col :span="16">
          <el-divider content-position="left">选购商品</el-divider>
          <el-table class="miui-table" ref="goodsTable" style="margin-bottom: 10px;" border :data="detailList"
            @selection-change="handleSelectionChange">
            <el-table-column v-if="isMeal">套</el-table-column>
            <el-table-column v-else type="selection" header-align="center" align="center" width="30"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="120" style="overflow: hidden;">
              <template slot-scope="scope">
                <div :title="scope.row.name" style="width: 120px;overflow: hidden;white-space: nowrap;">{{scope.row.name}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="goodsPrice" label="单价" width="60"></el-table-column>
            <el-table-column prop="storageQuantity" label="可用库存" width="55"></el-table-column>
            <el-table-column prop="goodsQuantity" label="数量" width="55">
              <template slot-scope="scope">
                <el-input v-if="scope.row.ctgId == '3'" v-model="scope.row.goodsQuantity" readonly></el-input>
                <el-input v-model="scope.row.goodsQuantity" v-else @input="change($event,scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="originalPrice" label="原价合计"></el-table-column>
            <el-table-column prop="discountRate" label="折扣率" width="60"></el-table-column>
            <el-table-column prop="discountPrice" label="折扣金额" width="55"></el-table-column>
            <el-table-column prop="receivablePrice" label="应收金额"></el-table-column>
            <el-table-column prop="goodsDescription" label="商品描述" width="80"></el-table-column>
            <el-table-column label="操作" width="75">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete" @click="deleteHandle(scope.row,'goodsDetail')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="16">
              <el-table class="miui-table" border :data="feeList">
                <el-table-column prop="name" label="附加费名称"></el-table-column>
                <el-table-column prop="price" label="金额" width="90"></el-table-column>
                <el-table-column prop="quantity" label="数量" width="70">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.quantity" @input="feeQuantityChange(scope.row.quantity,scope.$index)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="totalPrice" label="合计" width="90">
                  <template slot-scope="scope">￥{{scope.row.totalPrice}}</template>
                </el-table-column>
                <el-table-column label="删除" width="80">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteHandle(scope.row.feeId,'fee')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="8">
              <el-table class="miui-table" border :data="machingSelectList">
                <el-table-column prop="value" label="加工要求"></el-table-column>
                <el-table-column label="删除" width="60">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteHandle(scope.row.value,'maching')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-form>
              <el-form-item label="销售备注">
                <el-input v-model="sale.memo" style="width: 200px;"></el-input>
              </el-form-item>
              <!-- <el-form-item label="邮寄">
                <el-checkbox v-model="isMail" @change="mailChangeHandle">邮递信息</el-checkbox>
              </el-form-item> -->
            </el-form>

          </el-row>
        </el-col>
      </el-row>

      <!-- 结算 -->
      <div v-if="customerData.id" class="settlement-box" :class="isCollapse?'width1':'width2'">
        <el-form inline style="background-color: #ecf5ff;">
          <el-form-item label="原价合计">
            ￥{{sale.originalPrice || '0.00'}}
          </el-form-item>
          <el-form-item label="商品打折">
            <el-input style="width: 100px;" readonly @focus="discountOpen"></el-input>
            <!-- <el-button>还原</el-button> -->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-refresh-right" @click="discountReduction">还原</el-button>
          </el-form-item>
          <el-form-item label="折扣金额">
            ￥{{sale.discountPrice || '0.00'}}
          </el-form-item>
          <el-form-item label="抹零金额">
            <el-input style="width: 100px;" v-model="sale.removePrice" @change="computeMoney"></el-input>
          </el-form-item>
          <el-form-item label="应收金额">
            <el-input style="width: 100px;" v-model="sale.receivablePrice"></el-input>
          </el-form-item>
          <el-form-item label="福利">
            <el-select style="width: 100px;" v-model="sale.welfare">
              <el-option value="0" label="常规"></el-option>
              <el-option value="1" label="员工福利"></el-option>
              <el-option value="2" label="特批"></el-option>
              <el-option value="3" label="套餐"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="取镜方式">
            <el-select style="width: 100px;" v-model="takeTimeValue" @change="takeTypeChange">
              <el-option v-for="item in takeTimeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="取镜日期">
            <el-date-picker v-model="sale.takeMirroTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm" :clearable="false"></el-date-picker>
          </el-form-item>
          <el-form-item label="取镜地点">
            <el-popover placement="bottom" trigger="click" v-model="popoverVisible">
              <el-input slot="reference" style="width: 120px;" readonly v-model="saleOrderData.takeAddsName"></el-input>
              <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" default-expand-all
                :expand-on-click-node="false"></el-tree>
            </el-popover>
          </el-form-item>
          <el-form-item label="加急状态">
            <el-select v-model="sale.urgentStatus" style="width: 100px;">
              <el-option v-for="item in urgentOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-shopping-cart-1" @click="settlement" :loading="ischeck"
              v-prevent-re-click>结算</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <search-customer v-if="searchCustomerVisible" ref="searchCustomer" @refreshForm="getCustomerData"></search-customer>
    <detail-customer v-if="detailCustomerVisible" ref="detailCustomer"></detail-customer>
    <set-meal v-if="setMealVisible" ref="setMeal"></set-meal>
    <choice-meal v-if="choiceMealVisible" ref="choiceMeal"  @refreshForm="getMealData"></choice-meal>
    <goods-search v-if="goodsSearchVisible" ref="goodsSearch" @refreshForm="getGoodsData"></goods-search>
    <self-form v-if="selfVisible" ref="selfGoodsForm" @refreshForm="getGoodsData"></self-form>
    <customer-add v-if="customerAddVisible" ref="customerAdd" @refreshDataList="customerNewData"></customer-add>
    <discount v-if="discountVisible" ref="discountDislog" @refreshForm="getGoodsData"></discount>
    <gift-info v-if="giftInfoVisible" ref="giftInfo" @refreshForm="getgift"></gift-info>


  </div>
</template>

<script>
  import { getStore, setStore } from '@/util/store'
  import {
    add0,
    filterParams,
    timeCompute,
    uniqObjArrById,
    fomatFloat,
    deduplicationBykey
  } from '@/util/tools'
  import {
    fetchCtgList,
    delCtgObj,
    getCtgObj
  } from '@/api/eims/ctg'
  import { fetchTree } from '@/api/admin/dept'
  import {
    saleOptometryFetchList,
    getOptPortList,
    saleAddObj,
    getNowTime
  } from '@/api/eims/sale'
  import {
    getUserListByMenu,
    getUserByDeptIdAndJobType,
    getUserListByJobType
  } from '@/api/admin/user' // 获取销售人员列表,根据部门和职务类型获取工作人员列表
  import { fetchAddFeeList } from '@/api/eims/add-fee' //  获取附加费列表
  import { getCustomerByCardNo } from "@/api/eims/customer"

  import GiftInfo from "../giftsmanage/gift-search"
  import SearchCustomer from '@/components/business/customer-search' // 查询顾客
  import CustomerAdd from '@/views/eims/customer/form' //  新增会员
  import DetailCustomer from '@/views/eims/customer/detail' // 顾客详情
  import OptometryTable from './components/optometry-form' // 验光处方表
  import SendMail from './components/send-mail' // 邮寄信息
  import SetMeal from './components/set-meal' // 套餐信息
  import ChoiceMeal from './components/ChoiceMeal'
  import GoodsSearch from '@/components/business/goods-stock-search' // 库存商品查询
  import SelfForm from '@/components/business/self' //  自镜自架

  //  商品打折
  import Discount from '@/components/business/Discount'

  import { mapGetters, mapState } from 'vuex'
  export default {
    data() {
      return {
        ischeck: false,
        isMeal: false,
        isMail: false,      // 是否邮寄
        flag: 1,
        optometryFormEdit: true,
        saleUserOptions: [],
        optometristOptions: [],
        checkOptometryList: [],
        doctorOptions: [],
        dataListLoading: false,
        giftInfoVisible: false,
        activeName: 'first',
        popoverVisible: false,
        receivablePriceTotal: '',
        firstOriginalPriceTotal: '',
        dataForm: {
          customerId: '',
          optUserId: '',
          optUserName: ''
        },
        customerData: {
          customerCard: '',
          id: '',
          name: '',
          gender: '',
          age: '',
          phone1: '',
          cardType: '',
          integral: ''
        },
        saleOptometryList: [],
        saleOrderData: {
          takeAddsName: '',
          machingList: []
        },
        // 销售验光信息对象
        optometry: {
          optType: '1',
          optOutFlag: '1'
        },
        // 销售对象
        sale: {
          actulTakeMirroTime: '',
          checkFlag: '1', // 内部处方
          customerId: '', //  顾客ID
          discountPrice: 0, //  折扣金额
          discountType: '', //  折扣类型
          discountUserId: '', //  折扣员工ID
          memo: '', //  销售单备注
          originalPrice: 0, //  原价总金额
          receivablePrice: 0, //  应收金额
          removePrice: 0, //  抹零金额
          saleType: 4, //  销售类型
          salerUserId: '', //  销售员工
          optUserId: '', //  验光师
          setmealFlag: '0', //  是否是套餐
          setmealId: '', //  套餐
          takeMirroDeptId: '', //  取镜部门
          takeMirroTime: '', //  预计取镜时间
          urgentStatus: '1', //  加急状态
          workRequest: '', //  加工要求
          welfare: '0' //福利
        },
        //  销售详情对象列表
        detailList: [],
        feeList: [],
        gifList: [],
        treeData: [],
        total: {
          goods: 0,
          fee: 0
        },
        defaultProps: { children: 'children', label: 'name' },
        takeTimeValue: '1',
        takeTimeOptions: [
          { value: '1', label: '正常' },
          { value: '7', label: '定做7' },
          { value: '10', label: '定做10' },
          { value: '15', label: '定做15' },
          { value: '25', label: '定做25' }
        ],
        urgentOptions: [
          { value: '1', label: '正常' },
          { value: '2', label: '加急' }
        ],
        addfee: '',
        maching: '',
        machingSelectList: [],
        addFeeOptions: [],
        discountSelect: [],
        searchCustomerVisible: false,
        detailCustomerVisible: false,
        sendMailVisible: false,
        setMealVisible: false,
        choiceMealVisible: false,
        goodsSearchVisible: false,
        selfVisible: false,
        customerAddVisible: false,
        discountVisible: false
      }
    },
    components: {
      SearchCustomer,
      DetailCustomer,
      OptometryTable,
      SetMeal,
      ChoiceMeal,
      GoodsSearch,
      SelfForm,
      CustomerAdd,
      Discount,
      GiftInfo,
      SendMail
    },
    created() {
      this.initTakeTime('1')
      this.getTakeAddress()
      //  获取销售人员列表
      this.getSalesmanList()
      //	获取验光师列表
      this.getOptometristList()
    },
    computed: {
      ...mapGetters(['permissions', 'bizData', 'userInfo', 'tagList', 'tag', 'isCollapse']),
      ...mapState({
        showTag: state => state.common.showTag
      }),
    },
    methods: {
      // 打开弹窗
      openDialog(typeName, value, selfFlag) {
        switch (typeName) {
          case 'customer':
            this.searchCustomerVisible = true
            this.$nextTick(() => {
              this.$refs.searchCustomer.init()
            })
            break;
          case 'addNewCustomer':
            this.customerAddVisible = true
            this.$nextTick(() => {
              this.$refs.customerAdd.init()
            })
            break
          case 'customerDetail':
            this.detailCustomerVisible = true
            this.$nextTick(() => {
              this.$refs.detailCustomer.init(this.customerData.id, '会员详细')
            })
            break;
          case 'fillInSendMail':
            this.sendMailVisible = true
            this.$nextTick(() => {
              this.$refs.sendMail.init()
            })
            break
          case 'chooseSetMeal':
            if(!this.discountSelect.length){
              this.$message.warning('请选择商品')
              return false
            }
            let goodsIds = []
            goodsIds = this.discountSelect.map(item => item.goodsId)
            let data = {
              deptId: this.userInfo.lessDeptId,
              type: this.sale.saleType,
              goodsIds: goodsIds
            }
            this.choiceMealVisible = true
            this.$nextTick(() => {
              this.$refs.choiceMeal.init(data)
            })
            break;
          case 'checkSetMeal':
            this.setMealVisible = true
            this.$nextTick(() => {
              this.$refs.setMeal.init()
            })
            break
          case 'searchGoods':
            if (this.sale.saleType == '5') {
              if (value == '3' || value == '4') {
                this.$message.warning('辅料销售不能销售该类型的商品')
                return false
              }
              let list = []
              this.detailList.forEach((item, index) => {
                if (item.goodsDescription != '赠品') {
                  list.push(item)
                }
              })
              let data = {
                paramsData: {
                  ctgId: value,
                  selfFlag: selfFlag,
                },
                tableData: list
              }
              this.goodsSearchVisible = true
              this.$nextTick(() => {
                this.$refs.goodsSearch.init(data)
              })
            } else {
              this.$refs.optoTable.checkOptometryData().validate(valid => {
                if (valid) {
                  if (this.optometry.postGlassOd == '' || this.optometry.postGlassOd == null) {
                    this.$set(this.optometry, 'postGlassOd', '0.00')
                  }
                  if (this.optometry.postGlassOs == '' || this.optometry.postGlassOs == null) {
                    this.$set(this.optometry, 'postGlassOs', '0.00')
                  }
                  if (this.optometry.postGlassOd > 0) {
                    let ballGlassOd = (parseFloat(this.optometry.ballGlassOd) * 100 + parseFloat(this.optometry.postGlassOd) *
                      100) / 100
                    this.$set(this.optometry, 'ballGlassOd', ballGlassOd)
                    this.$set(this.optometry, 'postGlassOd', (0 - this.optometry.postGlassOd))
                    let axesOd = (parseFloat(this.optometry.axesOd) > 90) ? (parseFloat(this.optometry.axesOd) - 90) :
                      (parseFloat(this.optometry.axesOd) + 90)
                    this.$set(this.optometry, 'axesOd', axesOd)
                  }
                  if (this.optometry.postGlassOs > 0) {
                    let ballGlassOs = (parseFloat(this.optometry.ballGlassOs) * 100 + parseFloat(this.optometry.postGlassOs) *
                      100) / 100
                    this.$set(this.optometry, 'ballGlassOs', ballGlassOs)
                    this.$set(this.optometry, 'postGlassOs', (0 - this.optometry.postGlassOs))
                    let axesOs = (parseFloat(this.optometry.axesOs) > 90) ? (parseFloat(this.optometry.axesOs) - 90) :
                      (parseFloat(this.optometry.axesOs) + 90)
                    this.$set(this.optometry, 'axesOs', axesOs)
                  }
                  let list = []
                  this.detailList.forEach((item, index) => {
                    if (item.goodsDescription != '赠品') {
                      list.push(item)
                    }
                  })
                  let data = {
                    paramsData: {
                      ctgId: value,
                      selfFlag: selfFlag,
                      ballGlassOd: this.optometry.ballGlassOd, // 右眼球镜
                      ballGlassOs: this.optometry.ballGlassOs,
                      postGlassOd: this.optometry.postGlassOd, // 右眼柱镜
                      postGlassOs: this.optometry.postGlassOs,
                    },
                    tableData: list
                  }
                  this.goodsSearchVisible = true
                  this.$nextTick(() => {
                    this.$refs.goodsSearch.init(data)
                  })
                }
              })
            }
            break
        }
      },
      //  自镜自架
      selfGoods(type) {
        let data = {
          paramsData: {
            ctgId: type,
            selfFlag: 1
          },
          tableData: this.detailList
        }
        this.selfVisible = true
        this.$nextTick(() => {
          this.$refs.selfGoodsForm.init(data)
        })
      },
      //   新增会员
      customerNewData(data) {
        getCustomerByCardNo(data).then(response => {
					if(response.data.code == '0'){
					  this.refreshOptoAndSaleData(response.data.data)
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      //  根据会员卡号查看会员信息
      getCustomerByCardNo() {
        getCustomerByCardNo(this.customerData.customerCard).then(response => {
					if(response.data.code == '0'){
					  this.refreshOptoAndSaleData(response.data.data)
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      // 获取顾客信息
      getCustomerData(data) {
        this.refreshOptoAndSaleData(data)
      },
      //   刷新验光数据和销售数据(所有数据都要刷新)
      refreshOptoAndSaleData(data) {
        setStore({
          name: 'customerId',
          content: data.id,
          type: 'session'
        })
        this.customerData.id = ''
        //  销售类型改为框镜
        this.sale.saleType = 4
        //  销售人员改为登录人员
        this.sale.salerUserId = this.userInfo.id

        //  清空验光数据
        this.$nextTick(() => {
          for (let key in this.optometry) {
            if (key != 'optOutFlag') {
              this.optometry[key] = ''
            }
            this.optometry.optType = '1'
            this.optometry.createTime = timeCompute(new Date())
          }
        })

        this.initTakeTime('1')
        this.getAddFeeList() //  获取附加费列表
        //清空商品信息
        this.detailList = []
        this.gifList = []

        //清空原价合计，商品折扣等信息
        this.$set(this.sale, 'originalPrice', 0)
        this.$set(this.sale, 'discountPrice', 0)
        this.$set(this.sale, 'removePrice', 0)
        this.$set(this.sale, 'receivablePrice', 0)

        this.$set(this.sale, 'memo', '')

        //  获取顾客信息
        setTimeout(() => {
          this.customerData = data
          this.sale.customerId = data.id
          if (this.customerData.id) {
            //  获取顾客验光单
            this.getSaleOptomeryList()
            // 获取顾客视光检查单
            this.getCheckOptList()
          }
        }, 10)
      },
      // 销售类型改变事件
      saleTypeChange(val) {
        for (let key in this.optometry) {
          if (key != 'optOutFlag') {
            this.optometry[key] = ''
          }
        }
        
        //清空商品信息
        this.detailList = []
        this.gifList = []
        this.sale.memo = ''
        this.$set(this.sale, 'memo', '')
        this.optometry.createTime = timeCompute(new Date())
        this.clearOptometryForm()
        switch (val) {
          case 3:
            this.$set(this.optometry, 'optType', '3')
            break
          case 4:
            this.$set(this.optometry, 'optType', '1')
            break
          case 5:
            this.$set(this.optometry, 'optType', '')
            break
        }
      },
      //  内/外部处方
      optOutFlagChange(val) {
        this.$set(this.optometry, 'optOutFlag', val)
      },
      //  验光处方类型
      optTypeChange(val) {
        //清空验光信息
        for (let key in this.optometry) {
          if (key != 'createTime' && key != 'optOutFlag') {
            this.optometry[key] = ''
          }
        }
        //改变销售类型
        this.$set(this.optometry, 'optType', val)
        if (['1', '2', '4', '5'].includes(val)) {
          this.$set(this.sale, 'saleType', 4)
        } else if (['3', '6', '8', '9', '10'].includes(val)) {
          this.$set(this.sale, 'saleType', 3)
        } else if (['7', '11'].includes(val)) {
          this.$set(this.sale, 'saleType', 5)
        }
        //清控商品信息
        this.detailList = []
        this.gifList = []
        this.$set(this.sale, 'memo', '')
      },
      //  获取用户列表(销售人员)
      getSalesmanList() { // key = '1'
        let path = this.getPathByKey('1')
        getUserByDeptIdAndJobType({deptId:this.userInfo.lessDeptId,jobType:'1'}).then(response => {
					if(response.data.code == '0'){
					  this.saleUserOptions = response.data.data
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      //获取验光人员列表
      getOptometristList() {
        getUserByDeptIdAndJobType({deptId:this.userInfo.lessDeptId,jobType:'3'}).then(response => {
					if(response.data.code == '0'){
					  this.optometristOptions = response.data.data
					}else{
					  this.$message.error(response.data.msg)
					}
        })
        getUserListByJobType(7).then(response => {
					if(response.data.code == '0'){
					  this.doctorOptions = response.data.data
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      saleUserChange(val) {
        this.optometry.optUserId = val
      },
      // 主检医生
      checkDoctorChangeHandle(val) {
        let obj = this.doctorOptions.find(item => {
          return item.id == val
        })
        this.$set(this.sale, 'checkDoctorName', obj.realName)
      },
      // 获取顾客的验光处方表
      getSaleOptomeryList() {
        saleOptometryFetchList(filterParams({
          personId: this.customerData.personId,
          customerId: this.customerData.id
        })).then(response => {
					if(response.data.code == '0'){
					  this.saleOptometryList = response.data.data
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      getCheckOptList(){
        getOptPortList(this.customerData.personId).then(response => {
        	if(response.data.code == '0'){
        	  this.checkOptometryList = response.data.data
        	}else{
        	  this.$message.error(response.data.msg)
        	}
        })
      },
      // 选取验光处方
      handleCurrentChange(val) {
        this.optometry = JSON.parse(JSON.stringify(val))
        if (this.optometry) {
          if (['1', '2', '4', '5'].includes(this.optometry.optType)) {
            this.$set(this.sale, 'saleType', 4)
          } else if (['3', '6', '8', '9', '10'].includes(this.optometry.optType)) {
            this.$set(this.sale, 'saleType', 3)
          } else if (['7', '11'].includes(this.optometry.optType)) {
            this.$set(this.sale, 'saleType', 5)
          }

          //  判断验光单里的验光师是否存在
          let result = this.optometristOptions.some(item => {
            if (item.id == this.optometry.optUserId) {
              return true
            }
          })
          if (!result) {
            this.optometristOptions.push({
              id: this.optometry.optUserId,
              realName: this.optometry.optUserName
            })
          }
          this.optometristOptions = [...this.optometristOptions]
          this.$set(this.sale, 'optUserId', this.optometry.optUserId)
        }
        this.optometryFormEdit = false

        //清空商品信息
        this.detailList = []
        this.gifList = []
        this.$set(this.sale, 'memo', '')
      },
      handleCurrentChange1(val){
        let obj = {}
        if(val){
          let data = JSON.parse(JSON.stringify(val))
          if (['1', '2', '4', '5'].includes(data.goals)) {
            this.$set(this.sale, 'saleType', 4)
          } else if (['3', '6'].includes(data.goals)) {
            this.$set(this.sale, 'saleType', 3)
          } else if (['7'].includes(data.goals)) {
            this.$set(this.sale, 'saleType', 5)
          }
          obj = {
            ballGlassOd: data.balBallGlassOd,
            ballGlassOs: data.balBallGlassOs,
            postGlassOd: data.balPostGlassOd,
            postGlassOs: data.balPostGlassOs,
            axesOd: data.balAxesOd,
            axesOs: data.balAxesOs,
            farPupilDistanceOd: data.balInterHighOd,
            farPupilDistanceOs: data.balInterHighOs,
            nearPupilDistanceOd: data.balInterDistanceOd,
            nearPupilDistanceOs: data.balInterDistanceOs,
            pupilHighOd: data.pupilHeightOd,
            pupilHighOs: data.pupilHeightOs,
            farUseOd: data.balVaOd,
            farUseOs: data.balVaOs,
            optUserId: data.checker,
            optType: data.goals
          }
          this.optometry = obj
          this.$set(this.sale, 'optUserId', data.checker)
        }
        //清空商品信息
        this.detailList = []
        this.gifList = []
        this.$set(this.sale, 'memo', '')
      },
      //  清空验光信息
      clearOptometryForm() {
        let createTime = this.optometry.createTime
        if (this.sale.saleType != '5') {
          this.$refs.alreadyOPt.setCurrentRow()
        }
        // for(let key in this.optometry){
        //   this.optometry[key] = ''
        // }
        this.optometry = {
          optOutFlag: '1'
        }
        this.optometry.createTime = createTime
        this.optometryFormEdit = true

        //清空商品信息
        this.detailList = []
        this.gifList = []

        //清空原价合计，商品折扣等信息
        this.$set(this.sale, 'originalPrice', 0)
        this.$set(this.sale, 'discountPrice', 0)
        this.$set(this.sale, 'removePrice', 0)
        this.$set(this.sale, 'receivablePrice', 0)

        this.$set(this.sale, 'memo', '')
      },
      //  根据key值获取url
      getPathByKey(key) {
        let obj = {}
        obj = this.bizData.personTypeData.find(item => {
          if (item.key == key) {
            return item
          }
        })
        if (obj) {
          return obj.value
        }
      },
      // 数据类型转换
      getDataType(name, value) {
        let obj = {}
        obj = this.bizData[name].find(item => {
          return item.value == value
        })
        if (obj && obj.label) {
          return obj.label
        }
      },
      // 取镜日期截取
      cutStr(dateStr){
        if(dateStr){
          return dateStr.substr(0,10)
        }
      },
      takeTypeChange(val) {
        this.initTakeTime(val)
      },
      // 计算取镜时间
      initTakeTime(type) {
        getNowTime().then(result => {
          let nowDate = Number(new Date(result.data.data).getTime())
          // let nowTime = Number(new Date())
          let addTime
          switch (type) {
            case 1, '1':
              addTime = 7200000;
              break;
            case 7, '7':
              addTime = 86400000 * 7;
              break;
            case 10, '10':
              addTime = 86400000 * 10;
              break;
            case 15, '15':
              addTime = 86400000 * 15;
              break;
            case 25, '25':
              addTime = 86400000 * 25;
              break;
          }
          // this.sale.takeMirroTime = timeCompute(new Date(nowDate + addTime))
          this.$set(this.sale, 'takeMirroTime', timeCompute(new Date(nowDate + addTime)))
        })

      },
      // 获取取镜地点
      getTakeAddress() {
        this.sale.takeMirroDeptId = this.userInfo.lessDeptId
        this.saleOrderData.takeAddsName = this.userInfo.lessDeptName
        fetchTree(this.listQuery).then(response => {
          this.treeData = response.data.data
        })
      },
      // 部门树选中事件
      handleNodeClick(val) {
        this.popoverVisible = false
        this.sale.takeMirroDeptId = val.id
        this.saleOrderData.takeAddsName = val.name
      },
      change(e, row) {
        if (parseFloat(e) > parseFloat(row.storageQuantity)) {
          this.detailList.forEach((item, index) => {
            if (item.ctgId == '3') {
              if (item.goodsId == row.goodsId && item.glassFlag == row.glassFlag && item.goodsDescription == row.goodsDescription) {
                this.$set(item, 'goodsQuantity', item.storageQuantity)
              }
            } else if (item.ctgId == '4') {
              if (item.goodsId == row.goodsId && item.glassFlag == row.glassFlag && item.goodsDescription == row.goodsDescription &&
                item.batch == row.batch && item.invalidTime == row.invalidTime) {
                this.$set(item, 'goodsQuantity', item.storageQuantity)
              }
            } else if (item.ctgId == '5') {
              if (item.goodsId == row.goodsId && item.goodsDescription == row.goodsDescription && item.batch == row
                .batch && item.invalidTime == row.invalidTime) {
                this.$set(item, 'goodsQuantity', item.storageQuantity)
              }
            } else {
              if (item.goodsId == row.goodsId && item.goodsDescription == row.goodsDescription) {
                this.$set(item, 'goodsQuantity', item.storageQuantity)
              }
            }
          })
        }
        this.detailList = [...this.detailList]
        this.gifList = []
        this.getGoodsData(this.detailList)
      },
      //  附加费用数量变化
      feeQuantityChange(val, idx) {
        if (val % 1 != 0) {
          this.$set(this.feeList[idx], 'quantity', '')
          this.$message.warning('附加费用数量请输入整数')
          return
        }
        this.feeList[idx].totalPrice = this.feeList[idx].price * this.feeList[idx].quantity
        this.feeList = [...this.feeList]
        let sum = 0
        this.feeList.forEach((item, index) => {
          sum += Number(item.totalPrice)
        })
        this.total.fee = sum
        let originalPrice = this.total.fee + this.total.goods // 原价总金额
        let receivablePrice = (this.total.fee + this.receivablePriceTotal) - this.sale.removePrice // 应收、实收金额
        this.$set(this.sale, 'originalPrice', originalPrice)
        this.$set(this.sale, 'receivablePrice', receivablePrice)
      },
      // 获取商品信息
      getGoodsData(val) {
        let data = val.value || val
        let select = val.select || []
        this.$refs.goodsTable.clearSelection()
        if (select.length) {
          this.$nextTick(() => {
            select.forEach(item => {
              if (item.ctgId == '3') {
                for (let i = 0; i < this.detailList.length; i++) {
                  if (this.detailList[i].goodsId == item.goodsId && item.glassFlag == row.glassFlag && item.goodsDescription ==
                    row.goodsDescription) {
                    this.$refs.goodsTable.toggleRowSelection(this.detailList[i], true);
                  }
                }
              } else if (item.ctgId == '4') {
                for (let i = 0; i < this.detailList.length; i++) {
                  if (item.goodsId == row.goodsId && item.glassFlag == row.glassFlag && item.goodsDescription ==
                    row.goodsDescription && item.batch == row.batch && item.invalidTime == row.invalidTime) {
                    this.$refs.goodsTable.toggleRowSelection(this.detailList[i], true);
                  }
                }
              } else if (item.ctgId == '5') {
                for (let i = 0; i < this.detailList.length; i++) {
                  if (item.goodsId == row.goodsId && item.goodsDescription == row.goodsDescription && item.batch ==
                    row.batch && item.invalidTime == row.invalidTime) {
                    this.$refs.goodsTable.toggleRowSelection(this.detailList[i], true);
                  }
                }
              } else {
                for (let i = 0; i < this.detailList.length; i++) {
                  if (this.detailList[i].goodsId == item.goodsId) {
                    this.$refs.goodsTable.toggleRowSelection(this.detailList[i], true);
                  }
                }
              }
            });
          });
        }
        let list = data
        list.forEach((item, index) => {
          if (item.goodsDescription != '赠品') {
            // 原价合计
            if (item.originalPrice) {
              item.originalPrice = fomatFloat((item.firstOriginalPriceTotal * item.goodsQuantity), 2)
            } else {
              item.originalPrice = fomatFloat((item.goodsPrice * item.goodsQuantity), 2)
              item.firstOriginalPriceTotal = fomatFloat((item.goodsPrice * item.goodsQuantity), 2)
            }
            //若存在促销价则重新赋值销售单价
            if (item.promotionPrice) {
              item.goodsPrice = item.promotionPrice
              // 单个商品应收
              item.singleReceivable = fomatFloat((item.promotionPrice * item.discountRate), 4)
              // 单个商品折扣
              item.singleDiscount = fomatFloat((item.promotionPrice - item.singleReceivable), 4)
              // 折扣金额 = 单商品折扣 X 数量
              item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
              // 应收金额 = 原价合计 - 折扣金额
              item.receivablePrice = fomatFloat((item.promotionPrice * item.goodsQuantity - item.discountPrice), 2)
            } else {
              // 单个商品应收
              item.singleReceivable = fomatFloat((item.goodsPrice * item.discountRate), 4)
              // 单个商品折扣
              item.singleDiscount = fomatFloat((item.goodsPrice - item.singleReceivable), 4)
              // 折扣金额 = 单商品折扣 X 数量
              item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
              // 应收金额 = 原价合计 - 折扣金额
              item.receivablePrice = fomatFloat((item.originalPrice - item.discountPrice), 2)
            }
          }
          list[index] = filterParams(item)
        })


        // 计算表格中的金额数据
        this.detailList = list

        // this.detailList = deduplicationBykey(this.detailList.concat(this.gifList),'goodsId','glassFlag','goodsDescription','batch','invalidTime')
        let sum = 0
        let discount = 0
        let receivable = 0
        this.detailList.forEach(item => {
          sum += Number(item.originalPrice)
          discount += Number(item.discountPrice)
          receivable += Number(item.receivablePrice)
        })

        let fee = 0
        this.feeList.forEach(item => {
          fee += Number(item.price)
        })
        this.total.fee = fee
        this.total.goods = sum
        this.receivablePriceTotal = receivable
        this.sale.originalPrice = fomatFloat((this.total.goods + this.total.fee), 2)
        this.sale.discountPrice = fomatFloat(discount, 2)
        this.sale.receivablePrice = fomatFloat((this.receivablePriceTotal + this.total.fee - this.sale.removePrice), 2)

      },
      // 获取附加费用列表
      getAddFeeList() {
        fetchAddFeeList({
          current: 1,
          size: 100
        }).then(response => {
					if(response.data.code == '0'){
					  this.addFeeOptions = response.data.data.records
					}else{
					  this.$message.error(response.data.msg)
					}
        })
      },
      // 附加费用
      addFeeChange(val) {
        // 判断当前选项是否已存在
        let result = this.feeList.some(item => {
          if (item.feeId == val) {
            return true
          }
        })
        if (!result) {
          this.addFeeOptions.forEach(item => {
            if (item.id == val) {
              let obj = {}
              obj.feeId = item.id
              obj.name = item.name
              obj.price = item.fee
              obj.quantity = 1
              obj.totalPrice = obj.price * obj.quantity
              this.feeList.push(obj)
            }
          })
          let sum = 0
          this.feeList.forEach(item => {
            sum += Number(item.price)
          })
          this.total.fee = sum
          this.sale.originalPrice = this.total.fee + this.total.goods // 原价总金额
          this.sale.receivablePrice = this.receivablePriceTotal + this.total.fee - this.sale.removePrice // 应收、实收金额
        } else {
          this.$message.warning('当前附加项已添加！')
        }
      },
      machIngChange(val) {
        if (this.saleOrderData.machingList.indexOf(val) == -1) {
          this.saleOrderData.machingList.push(val)
          this.bizData.processingRequirementsData.forEach(item => {
            if (item.value == val) {
              this.machingSelectList.push(item)
            }
          })
        } else {
          this.$message.warning('该加工要求已经添加过了')
        }
      },
      computeMoney(val) {
        if (val > 10) {
          this.sale.removePrice = 0
          this.$message.warning('抹零金额超出最大设定金额')
          return false
        }
        this.sale.receivablePrice = fomatFloat((this.receivablePriceTotal + this.total.fee - val), 2)
      },
      // 删除
      deleteHandle(val, str) {
        switch (str) {
          case 'fee':
            this.feeList.splice(val)
            let sum1 = 0
            this.feeList.forEach((item, index) => {
              if (item.feeId == val) {
                this.feeList.splice(index, 1)
              }
            })
            this.feeList.forEach((item, index) => {
              sum1 += Number(item.totalPrice)
            })

            this.total.fee = sum1
            let originalPrice = sum1 + this.total.goods // 原价总金额
            let receivablePrice = (sum1 + this.receivablePriceTotal) - this.sale.removePrice // 应收、实收金额
            this.$set(this.sale, 'originalPrice', originalPrice)
            this.$set(this.sale, 'receivablePrice', receivablePrice)

            break
          case 'goodsDetail':
            // this.detailList = this.detailList.filter(t => t.goodsId != val.id )
            let goodsId = val.id || val.goodsId
            this.detailList.forEach((item, index) => {
              if (item.ctgId == 3 || item.ctgId == 4) {
                if (item.goodsId == val.goodsId && item.glassFlag == val.glassFlag && item.goodsDescription == val.goodsDescription) {
                  this.detailList.splice(index, 1)
                }
              } else {
                if (item.goodsId == val.goodsId && item.goodsDescription == val.goodsDescription) {
                  this.detailList.splice(index, 1)
                }
              }
            })

            if(this.detailList.length == 0){
              this.isMeal = false
            }

            this.detailList.forEach((item, index) => {
              // 原价合计
              if (item.originalPrice) {
                item.originalPrice = fomatFloat((item.firstOriginalPriceTotal * item.goodsQuantity), 2)
              } else {
                item.originalPrice = fomatFloat((item.goodsPrice * item.goodsQuantity), 2)
                item.firstOriginalPriceTotal = fomatFloat((item.goodsPrice * item.goodsQuantity), 2)
              }
              // // 单个商品应收 = 单价 X 折扣率
              // item.singleReceivable = fomatFloat((item.goodsPrice * item.discountRate),4)
              // // 单个商品折扣额 = 单价 - (单价 X 税率) /  单价 - 单个商品应收
              // item.singleDiscount = fomatFloat(item.goodsPrice - (item.goodsPrice * item.discountRate),4)

              // // 折扣金额 = 单个商品折扣额 * 数量
              // item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity),2)

              // // 应收金额 = 原价合计 - 折扣金额
              // item.receivablePrice = fomatFloat((item.originalPrice - item.discountPrice),2)
              //若存在促销价则重新赋值销售单价
              if (item.promotionPrice) {
                item.goodsPrice = item.promotionPrice
                // 单个商品应收
                item.singleReceivable = fomatFloat((item.promotionPrice * item.discountRate), 4)
                // 单个商品折扣
                item.singleDiscount = fomatFloat((item.promotionPrice - item.singleReceivable), 4)
                // 折扣金额 = 单商品折扣 X 数量
                item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
                // 应收金额 = 原价合计 - 折扣金额
                item.receivablePrice = fomatFloat((item.promotionPrice * item.goodsQuantity - item.discountPrice),
                  2)
              } else {
                // 单个商品应收
                item.singleReceivable = fomatFloat((item.goodsPrice * item.discountRate), 4)
                // 单个商品折扣
                item.singleDiscount = fomatFloat((item.goodsPrice - item.singleReceivable), 4)
                // 折扣金额 = 单商品折扣 X 数量
                item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
                // 应收金额 = 原价合计 - 折扣金额
                item.receivablePrice = fomatFloat((item.originalPrice - item.discountPrice), 2)
              }
              if (item.goodsDescription == '赠品') {
                item.receivablePrice = '0.00'
              }
            })
            let fee = 0
            this.feeList.forEach((item, index) => {
              if (item.feeId == val) {
                this.feeList.splice(index, 1)
              }
            })
            this.feeList.forEach((item, index) => {
              fee += Number(item.totalPrice)
            })

            // 计算表格中的金额数据
            let sum = 0
            let discount = 0
            let receivable = 0
            this.detailList.forEach(item => {
              sum += Number(item.originalPrice)
              discount += Number(item.discountPrice)
              receivable += Number(item.receivablePrice)
            })
            this.total.goods = sum
            this.total.fee = fee
            this.receivablePriceTotal = receivable
            this.sale.originalPrice = fomatFloat((this.total.goods + this.total.fee), 2)
            this.sale.discountPrice = fomatFloat(discount, 2)
            this.sale.receivablePrice = fomatFloat((this.receivablePriceTotal + this.total.fee - this.sale.removePrice),2)

            break
          case 'maching':
            this.saleOrderData.machingList.splice(val)
            this.machingSelectList.forEach((item, index) => {
              if (item.value == val) {
                this.machingSelectList.splice(index, 1)
              }
            })
            break
        }
      },
      // 获取选择套餐数据
      getMealData(data){
        let rate = 1
        this.isMeal = true
        this.sale.welfare = '3'
        switch(data.type){
          case 2:
            // 打折  // 直接计算折扣
            // do some data.typeInfo
            rate = data.typeInfo
            break
          case 3:
            // 返现	// 原价
            // do some
            rate = (this.sale.originalPrice - data.typeInfo) / this.sale.originalPrice
            break
          case 4:
            // 特价
            // do some
            rate = data.typeInfo / this.sale.originalPrice
            break
        }

        this.detailList.forEach(item => {
          item.discountRate = rate
          // 单个商品应收
          item.singleReceivable = fomatFloat((item.goodsPrice * rate), 4)
          // 单个商品折扣
          item.singleDiscount = fomatFloat((item.goodsPrice - item.singleReceivable), 4)
          // 折扣金额 = 单商品折扣额 X 数量
          item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
          // 应收金额 = 原价合计 - 折扣金额
          item.receivablePrice = fomatFloat((item.originalPrice - item.discountPrice), 2)
        })

        let fee = 0
        this.feeList.forEach((item, index) => {
          if (item.feeId == val) {
            this.feeList.splice(index, 1)
          }
        })
        this.feeList.forEach((item, index) => {
          fee += Number(item.totalPrice)
        })

        // 计算表格中的金额数据
        let sum = 0
        let discount = 0
        let receivable = 0
        this.detailList.forEach(item => {
          sum += Number(item.originalPrice)
          discount += Number(item.discountPrice)
          receivable += Number(item.receivablePrice)
        })
        this.total.goods = sum
        this.total.fee = fee
        this.receivablePriceTotal = receivable
        this.sale.originalPrice = fomatFloat((this.total.goods + this.total.fee), 2)
        this.sale.discountPrice = fomatFloat(discount, 2)
        this.sale.receivablePrice = fomatFloat((this.receivablePriceTotal + this.total.fee - this.sale.removePrice),2)
      },
      // 套餐还原
      restore(){
        this.isMeal = false
        this.sale.welfare = '0'
        this.detailList.forEach(item => {
          item.discountRate = 1
          // 单个商品应收
          item.singleReceivable = fomatFloat((item.goodsPrice * item.discountRate), 4)
          // 单个商品折扣
          item.singleDiscount = fomatFloat((item.goodsPrice - item.singleReceivable), 4)
          // 折扣金额 = 单商品折扣额 X 数量
          item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)
          // 应收金额 = 原价合计 - 折扣金额
          item.receivablePrice = fomatFloat((item.originalPrice - item.discountPrice), 2)
        })

        let fee = 0
        this.feeList.forEach((item, index) => {
          if (item.feeId == val) {
            this.feeList.splice(index, 1)
          }
        })
        this.feeList.forEach((item, index) => {
          fee += Number(item.totalPrice)
        })

        // 计算表格中的金额数据
        let sum = 0
        let discount = 0
        let receivable = 0
        this.detailList.forEach(item => {
          sum += Number(item.originalPrice)
          discount += Number(item.discountPrice)
          receivable += Number(item.receivablePrice)
        })
        this.total.goods = sum
        this.total.fee = fee
        this.receivablePriceTotal = receivable
        this.sale.originalPrice = fomatFloat((this.total.goods + this.total.fee), 2)
        this.sale.discountPrice = fomatFloat(discount, 2)
        this.sale.receivablePrice = fomatFloat((this.receivablePriceTotal + this.total.fee - this.sale.removePrice),2)
      },
      //  查找tag标签
      findTag(value) {
        let tag, key
        this.tagList.map((item, index) => {
          if (item.value === value) {
            tag = item
            key = index
          }
        })
        return {
          tag: tag,
          key: key
        }
      },
      //  配镜单提交
      settlement() {
        if (!this.sale.checkDoctorId) {
          this.$message.warning('请选择主检医生')
          return false
        }
        //  判断验光师和验光类型
        if (this.sale.saleType != 5) {
          if (this.optometry.optOutFlag == '1') {
            if (!this.sale.optUserId) {
              this.sale.optUserId = 9193
              // this.$message.warning('请选择验光师')
              // return false
            }
            if (!this.optometry.optType) {
              this.$message.warning('请选择验光类型')
              return false
            }
          } else {
            if (!this.sale.optUserId) {
              this.sale.optUserId = 9193
            }
          }
        }
        //  9193 外部验光师
        // 判断商品数量
        if (this.sale.saleType == '4') { // 框镜销售判断商品数量
          let ctg1 = []
          let ctg3 = []
          let ctg6 = []
          let ctg8 = []
          this.detailList.forEach(item => {
            if (item.ctgId == '3') {
              ctg3.push(item)
            } else if (item.ctgId == '1') {
              ctg1.push(item)
            } else if (item.ctgId == '6') {
              ctg6.push(item)
            } else if (item.ctgId == '8') {
              ctg8.push(item)
            }
          })
          if (ctg1.length < 1 && ctg6.length < 1 && ctg8.length < 1) {
            this.$message.warning('镜架、太阳镜、老花镜数量不足（框镜销售至少包含 镜架*1 镜片*2）')
            return false
          }
          if (ctg3.length < 2) {
            this.$message.warning('镜片数量不足（框镜销售至少包含 镜架*1 镜片*2）')
            return false
          }
        }

        this.detailList.forEach((item, index) => {
          delete this.detailList[index].id
        })
        this.sale.workRequest = this.saleOrderData.machingList.toString()
        this.optometry.optUserId = this.sale.optUserId
        this.optometry.optUserName = this.optometristOptions.forEach(item => {
          if (item.id == this.optometry.optUserId) {
            return item.realName
          }
        })
        this.sale.customerId = getStore({
          name: 'customerId'
        })
        let name = {}
        name = this.optometristOptions.find(item => {
          return item.id == this.optometry.optUserId
        })
        if (name && name.realName) {
          this.optometry.optUserName = name.realName
        }
        // for(let i = 0; i < this.detailList.length;i++){
        //   if(this.detailList[i].goodsQuantity > this.detailList[i].storageQuantity){
        //     this.$message.warning(this.detailList[i].goodsDescription + '库存不足，请检查商品数量')
        //     return false
        //   }
        // }
        let params = {
          optometry: filterParams(this.optometry),
          sale: filterParams(this.sale),
          detailList: this.detailList,
          feeList: this.feeList
        }
        this.ischeck = true
        saleAddObj(params).then(response => {
					if(response.data.code == '0'){
					  this.$message.success(response.data.data)
					  setTimeout(() => {
					    this.ischeck = false
					    this.$router.push('/eims/cashier/payment/index')
					    let {
					      tag,
					      key
					    } = this.findTag('/eims/sale/index')
					    this.$store.commit('DEL_TAG', tag)
					  }, 1000)
					}else{
						this.ischeck = false
					  this.$message.error(response.data.msg)
					}
        }).catch(() => {
          this.ischeck = false
        })
      },
      //  折扣
      discountOpen() {
        if (this.discountSelect.length) {
          let data = {
            selectGoods: this.discountSelect,
            tableData: this.detailList
          }
          this.discountVisible = true
          this.$nextTick(() => {
            this.$refs.discountDislog.init(data)
          })
        } else {
          this.$message.warning('请选择商品')
        }
      },
      //  折扣还原
      discountReduction() {
        let goodsList = this.discountSelect
        let tableData = this.detailList
        if (goodsList && goodsList.length) {
          goodsList.forEach((item, index) => {
            if (['3', '4'].includes(item.ctgId)) {
              for (let i = 0; i < tableData.length; i++) {
                if (tableData[i].goodsId == item.goodsId && tableData[i].glassFlag == item.glassFlag) {
                  tableData[i].discountRate = 1
                }
              }
            } else {
              for (let i = 0; i < tableData.length; i++) {
                if (tableData[i].goodsId == item.goodsId) {
                  tableData[i].discountRate = 1
                }
              }
            }
          })
          let data = {
            value: tableData,
            select: goodsList
          }
          this.getGoodsData(data)
          this.$nextTick(() => {
            this.$refs.goodsTable.clearSelection()
          })
        } else {
          this.$message.warning('请选择商品')
        }
      },
      handleSelectionChange(val) {
        this.discountSelect = val
      },
      openGiftInfo() {
        this.giftInfoVisible = true
        let list = []
        this.detailList.forEach((item, index) => {
          if (item.goodsDescription == '赠品') {
            list.push(item)
          }
        })

        this.$nextTick(() => {
          this.$refs.giftInfo.init(list)
        })
      },
      getgift(data) {
        let list = []
        if (data.length) {
          data.forEach((item, index) => {
            item.goodsPrice = item.price
            item.name = item.goodsName
            item.goodsQuantity = 1
            item.discountRate = 1
            item.goodsDescription = "赠品"
            let result = this.detailList.some(obj => {
              if (obj.goodsId == item.goodsId && obj.goodsDescription == item.goodsDescription && item.goodsDescription ==
                '赠品') {
                return true
              }
            })
            if (!result) {
              this.gifList.push(item)
              this.detailList.push(item)
            }
            this.detailList.forEach((item, index) => {
              if (item.goodsDescription == '赠品') {
                // 原价合计
                item.originalPrice = fomatFloat((item.goodsPrice * item.goodsQuantity), 2)
                // 单个商品应收 = 单价 X 折扣率
                item.singleReceivable = fomatFloat((item.goodsPrice * item.discountRate), 4)
                // 单个商品折扣额 = 单价 - (单价 X 税率) /  单价 - 单个商品应收
                item.singleDiscount = fomatFloat(item.goodsPrice - (item.goodsPrice * item.discountRate), 4)

                // 折扣金额 = 单个商品折扣额 * 数量
                item.discountPrice = fomatFloat((item.singleDiscount * item.goodsQuantity), 2)

                // 应收金额 = 原价合计 - 折扣金额
                item.receivablePrice = 0.00
              }
            })
          })
        }
        this.detailList = [...this.detailList]
      },
      // 邮寄信息
      mailChangeHandle(val){
        console.log(val)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .margin-right10 {
    margin-right: 10px;
    margin-left: 0;
  }

  .margin-top15 {
    margin-top: 15px;
  }

  .el-divider--horizontal {
    margin: 12px 0;
  }

  .miui-table {
    .table-input {
      width: 50px;
    }

    tr td,
    tr th {
      border: 2px solid #EFEEF5;
      text-align: center;
      padding: 3px 5px;
    }

    .colspan-td {
      text-align: left !important;
    }
  }

  .settlement-box {
    position: fixed;
    bottom: 0;
    // height: 130px;
    background-color: #ecf5ff;
    padding-left: 15px;
    z-index: 100;
  }

  .settlement-box.width1 {
    left: 70px;
    width: calc(100% - 80px)
  }

  .settlement-box.width2 {
    left: 250px;
    width: calc(100% - 260px);
  }

  // 隐藏菜单
  @media screen and (max-width: 992px) {
    .settlement-box.width1 {
      left: 10px;
      width: 100%;
    }

    .settlement-box.width2 {
      left: 10px;
      width: 100%;
    }
  }
</style>
